using Microsoft.SharePoint.Administration;
using System;
using RealDolmen.SharePoint.Helpers;
using Microsoft.SharePoint;

namespace RealDolmen.SharePoint.ListFeatures
{
    public class ListFeatureJobDefinition : SPJobDefinition
    {
        #region Variables
        [Persisted]
        private string listFeatureTrackerData;
        #endregion // Variables
        
        #region Properties
        /*
        protected ListFeature ListFeature
        {
            get { return listFeature; }
            set { listFeature = value; }
        }
         */

        public string ListFeatureTrackerData
        {
            get { return listFeatureTrackerData; }
            set { listFeatureTrackerData = value; }
        }

        #endregion // Properties
        
        #region Constructors
        public ListFeatureJobDefinition() 
            : base() {}
        public ListFeatureJobDefinition(string name, SPWebApplication webApplication, SPServer server, SPJobLockType lockType)
            : base(name, webApplication, server, lockType) {}
        #endregion // Constructors

        #region Business Methods
        public override void Execute(Guid targetInstanceId)
        {
            SPWeb web;
            SPSite site;
            ListFeature listFeature = ListFeatureTracker.Instantiate(ListFeatureTrackerData).OpenListFeature(out web, out site);

            if (listFeature != null)
            {
                if (listFeature.IsActive)
                {
                    listFeature.Register(this);
                    Execute(targetInstanceId, listFeature);
                    SPHelper.TryDisposeWeb(web);
                    SPHelper.TryDisposeSite(site);
                }
            }
        }

        public virtual void Execute(Guid targetInstanceId, ListFeature listFeature)
        {
            throw new InvalidOperationException();
        }
	    #endregion // Business Methods
    }
}
